package com.ruoyi.teacher.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.teacher.mapper.DepartmentMapper;
import com.ruoyi.teacher.domain.Department;
import com.ruoyi.teacher.service.IDepartmentService;
import org.springframework.util.CollectionUtils;

/**
 * 部门管理Service业务层处理
 * 
 * @author TengZeng
 * @date 2023-05-18
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService 
{
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 查询部门管理
     * 
     * @param id 部门管理主键
     * @return 部门管理
     */
    @Override
    public Department selectDepartmentById(Long id)
    {
        return departmentMapper.selectDepartmentById(id);
    }

    /**
     * 查询部门管理列表
     * 
     * @param department 部门管理
     * @return 部门管理
     */
    @Override
    public List<Department> selectDepartmentList(Department department)
    {
        return departmentMapper.selectDepartmentList(department);
    }

    /**
     * 新增部门管理
     * 
     * @param department 部门管理
     * @return 结果
     */
    @Override
    public int insertDepartment(Department department)
    {
        return departmentMapper.insertDepartment(department);
    }

    /**
     * 修改部门管理
     * 
     * @param department 部门管理
     * @return 结果
     */
    @Override
    public int updateDepartment(Department department)
    {
        return departmentMapper.updateDepartment(department);
    }

    /**
     * 批量删除部门管理
     * 
     * @param ids 需要删除的部门管理主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentByIds(Long[] ids)
    {
        return departmentMapper.deleteDepartmentByIds(ids);
    }

    /**
     * 删除部门管理信息
     * 
     * @param id 部门管理主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentById(Long id)
    {
        return departmentMapper.deleteDepartmentById(id);
    }

    /**
     * 部门树
     * @return
     */
    @Override
    public List<Department> getDeptTree() {

        List<Department> result = new ArrayList<>();
        // 查询出来所有
        List<Department> allDepartment = departmentMapper.findAll();
        // 转成map key id value department
        Map<Long, Department> departmentMap = allDepartment.stream().collect(Collectors.toMap(Department::getId, m -> m));
        // 遍历集合
        allDepartment.forEach(mu -> {
            if (null == mu.getParentId()) {
                result.add(mu);
            } else {
                Department parent = departmentMap.get(mu.getParentId());
                parent.getChildren().add(mu);
            }
        });
        return result;
    }

    
}
